<template>
  <div class="clearfix">
    <a-upload
      list-type="picture-card"
      :file-list="files"
      :beforeUpload="beforeUpload"
      @preview="handlePreview"
      @change="handleChange"
      :accept="imageTypes"
      :remove="removeImage">
      <div v-if="showUpload">
        <a-icon type="plus"/>
        <div class="ant-upload-text">
          上传图片
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>

<script>
// import cloneDeep from 'lodash.clonedeep'
import oss from './oss.js'
import { v4 as uuidv4 } from 'uuid'

export default {
  name: 'OssMultipleImage',
  mixins: [oss],
  props: {
    fileList: {
      type: Array
    },
    maxLength: {
      type: Number,
      default: 20,
      required: false
    }
  },
  data () {
    return {
      previewVisible: false,
      previewImage: '',
      files: [],
      imageTypes: '.jpg,.png,.jpeg,.bmp,.gif'
    }
  },
  computed: {
    showUpload () {
      const { files, maxLength } = this
      return !files || files.length < maxLength
    }
  },
  methods: {
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      // this.$emit('filesChange', fileList)
    },
    beforeUpload (file, fileList) {
      this.upload(file)
      return false
    },
    async upload (file) {
      const { files = [] } = this
      const filename = file.name
      const uuid = uuidv4()
      const objectKey = `shop/1/images/${uuid}${filename.substring(filename.lastIndexOf('.'), filename.length)}`
      const result = await this.putObject(objectKey, file)
      if (result && result.res.statusCode === 200) {
        files.push({
          uid: uuid,
          name: result.name,
          status: 'done',
          url: result.url
        })
        this.$emit('filesChange', files)
      }
    },
    removeImage (file) {
      const index = this.files.findIndex(listFile => file.uid === listFile.uid)
      this.delete(file.name)
      this.files.splice(index, 1)
      this.$emit('filesChange', this.files)
      return false
    }
  },
  watch: {
    fileList: {
      deep: true,
      handler (val) {
        this.files = val
      }
    }
  }
}
</script>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
